package com.unlcn.ils.sales.backend.service;

import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.sales.backend.bo.PickPwdBO;
import com.unlcn.ils.sales.backend.bo.UserViewBO;
import com.unlcn.ils.sales.backend.security.JwtAuthenicationFilter;
import com.unlcn.ils.sales.base.mapper.SalePickPwdMapper;
import com.unlcn.ils.sales.base.model.SalePickPwd;
import com.unlcn.ils.sales.base.model.SalePickPwdExample;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * Created by houjianhui on 2017/6/8.
 */
@Service
public class PickPwdServiceImpl implements PickPwdService{

    private static final Logger LOGGER = LoggerFactory.getLogger(PickPwdServiceImpl.class);

    @Autowired
    private SalePickPwdMapper pickPwdMapper;

    @Autowired
    private Md5PasswordEncoder passwordEncoder;

    @Autowired
    private JwtAuthenicationFilter jwtAuthenticationFilter;

    @Autowired
    private UserService userService;

    @Override
    public Boolean isSettingPwd() throws Exception {
        UserViewBO user = userService.getCurrentUser();
        SalePickPwd pickPwd = getPickPwd(user.getId());
        if (!Objects.equals(pickPwd, null)) {
            return true;
        }
        return false;
    }

    private SalePickPwd getPickPwd(Integer userId) {
        SalePickPwdExample example = new SalePickPwdExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<SalePickPwd> pwds;
        try {
            pwds = pickPwdMapper.selectByExample(example);
        } catch (Exception e) {
            LOGGER.error("PickPwdServiceImpl.getPickPwd error: {}", e);
            throw new BusinessException("查询提现密码异常");
        }
        if (CollectionUtils.isNotEmpty(pwds)) {
            return pwds.get(0);
        }
        return null;
    }

    @Override
    public Integer getErrorAmtByUserId() throws Exception {
        UserViewBO user = userService.getCurrentUser();
        SalePickPwd pickPwd = getPickPwd(user.getId());
        if (!Objects.equals(pickPwd, null)) {
            return pickPwd.getErrorAmt();
        }
        return 0;
    }

    @Override
    public Integer updateErrorAmt(Integer errorAmt) throws Exception {
        LOGGER.info("PickPwdServiceImpl.updateErrorAmt param errorAmt: {}", errorAmt);
        UserViewBO user = userService.getCurrentUser();
        SalePickPwd pickPwd = getPickPwd(user.getId());
        if (!Objects.equals(pickPwd, null)) {
            pickPwd.setErrorAmt(errorAmt);
            try {
                pickPwdMapper.updateByPrimaryKeySelective(pickPwd);
            } catch (Exception e) {
                LOGGER.error("PickPwdServiceImpl.updateErrorAmt error: {}", e);
                throw new BusinessException("更新提现密码输入错误次数异常");
            }
        }
        return null;
    }

    @Override
    public Integer save(PickPwdBO bo) throws Exception {
        LOGGER.info("PickPwdServiceImpl.save param PickPwdBO: {}", bo);
        if (Objects.equals(bo, null) || Objects.equals(bo, "")) {
            LOGGER.info("PickPwdServiceImpl.save param userId must not be null");
            throw new IllegalArgumentException("用户提现密码信息不能为空");
        }
        UserViewBO user = userService.getCurrentUser();
        bo.setUserId(user.getId());
        if (isSettingPwd(bo.getUserId())) {
            LOGGER.info("PickPwdServiceImpl.save Can't repeat set withdrawal password");
            throw new IllegalArgumentException("用户提现密码不能重复设置");
        }
        SalePickPwd pickPwd = new SalePickPwd();
        BeanUtils.copyProperties(bo, pickPwd);
        // 设置密码
        pickPwd.setPwd(passwordEncoder.encodePassword(bo.getPwd(), jwtAuthenticationFilter.getSecureKey()));
        try {
            pickPwdMapper.insertSelective(pickPwd);
        } catch (Exception e) {
            LOGGER.error("PickPwdServiceImpl.save error: {}", e);
            throw new BusinessException("设置用户提现密码异常");
        }
        return pickPwd.getId();
    }

    public Boolean isSettingPwd(Integer userId) throws Exception {
        SalePickPwd pickPwd = getPickPwd(userId);
        if (!Objects.equals(pickPwd, null)) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean verificationPickPwd(String pwd) throws Exception {
        LOGGER.info("PickPwdServiceImpl.verificationPickPwd param pwd: {}", pwd);
        if (Objects.equals(pwd, null) || Objects.equals(pwd, "")) {
            LOGGER.info("PickPwdServiceImpl.verificationPickPwd param pwd must not be null");
            throw new IllegalArgumentException("用户提现密码不能为空");
        }
        UserViewBO user = userService.getCurrentUser();
        SalePickPwd pickPwd = getPickPwd(user.getId());
        if (!Objects.equals(pickPwd, null)) {
            String pw = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
            if (pickPwd.getPwd().equals(pw)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Integer updatePickPwd(String pwd) throws Exception {
        LOGGER.info("PickPwdServiceImpl.updatePickPwd param pwd: {}", pwd);
        if (Objects.equals(pwd, null) || Objects.equals(pwd, "")) {
            LOGGER.info("PickPwdServiceImpl.updatePickPwd param pwd must not be null");
            throw new IllegalArgumentException("用户提现密码不能为空");
        }
        UserViewBO user = userService.getCurrentUser();
        SalePickPwd pickPwd = getPickPwd(user.getId());
        if (!Objects.equals(pickPwd, null)) {
            pickPwd.setPwd(passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey()));
            try {
                pickPwdMapper.updateByPrimaryKeySelective(pickPwd);
            } catch (Exception e) {
                LOGGER.error("PickPwdServiceImpl.updatePickPwd error: {}", e);
                throw new BusinessException("更新提现密码异常");
            }
        } else {
            throw new BusinessException("没有设置提现密码，请先设置提现密码");
        }
        return null;
    }
}
